package com.learn.admin.modules.sys.web;

import com.learn.admin.common.config.Global;
import com.learn.admin.common.utils.CookieUtils;
import com.learn.admin.common.web.BaseController;
import com.learn.admin.modules.sys.security.SystemAuthorizingRealm;
import com.learn.admin.modules.sys.utils.UserUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
public class LoginController extends BaseController {

    @RequestMapping(value = "${adminPath}/login", method = RequestMethod.GET)
    public String login(HttpServletRequest request, HttpServletResponse response, Model model) {
        SystemAuthorizingRealm.Principal principal = UserUtils.getPrincipal();
        if (Global.TRUE.equals(Global.getConfig("notAllowRefreshIndex"))) {
            CookieUtils.setCookie(response, "LOGINED", "false");
        }
        if (principal != null && !principal.isMobileLogin()) {
            return "redirect:" + adminPath;
        }
        return "modules/sys/sysLogin";
    }

    @RequestMapping(value = "${adminPath}")
    public String index(HttpServletRequest request, HttpServletResponse response) {
        SystemAuthorizingRealm.Principal principal = UserUtils.getPrincipal();
        // TODO 登录成功后,验证码计算器清零
        if (Global.TRUE.equals(Global.getConfig("notAllowRefreshIndex"))) {
            String logined = CookieUtils.getCookie(request, "LOGINED");
            if (StringUtils.isBlank(logined) || "false".equals(logined)) {
                CookieUtils.setCookie(response, "LOGINED", "true");
            } else {
                UserUtils.getSubject().logout();
                return "redirect:" + adminPath + "/login";
            }
        }
        return "modules/sys/sysIndex";
    }
}
